import re
import random
import hashlib

def check_token(token):
    return re.match('^[A-Za-z0-9]{3,32}$', token)

def generate_token(length=''):
    if not length:
        length = random.randint(3, 32)
    length = int(length)
    assert 3 <= length <= 32
    token = []
    letters = 'abcdefghijklmnopqrstuvwxyz' \
              'ABCDEFGHIJKLMNOPQRSTUVWXYZ' \
              '0123456789'
    for _ in range(length):
        token.append(random.choice(letters))
    return ''.join(token)

def _check_signature(signature, token, timestamp, nonce):
    sign = [token, timestamp, nonce]
    sign.sort()
    sign = '%s%s%s' % tuple(sign)
    sign = hashlib.sha1(sign).hexdigest()
    return sign == signature
